package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.BeneficiarioService;
import co.gov.medellin.ssti.sub.model.service.VflexService;
import co.gov.medellin.ssti.sub.model.vo.BeneficiarioVO;
import co.gov.medellin.ssti.sub.model.vo.VflexVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;

public class ConsultarBeneficiarioAction extends Action {
	@Autowired
	BeneficiarioService beneficiarioServiceImpl;
	@Autowired
	VflexService vflexServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		System.out.println("consultarBenef");

		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			BeneficiarioVO objBeneVO = new BeneficiarioVO();
			String strCode = request.getParameter("code");

			HttpSession session = request.getSession();
			Collection<BeneficiarioVO> beneSelected = new ArrayList<BeneficiarioVO>();
			List beneficiariosList = (List) session
					.getAttribute("beneficiarios");
			// List beneficiariosList =
			// (List)request.getAttribute("beneficiarios");
			Collection<VflexVO> comunas = null;
			Collection<VflexVO> barrios = null;
			Collection<VflexVO> zonas = null;
			Collection<VflexVO> hechosVictimizantes = null;

			String opcion = request.getParameter("opcion");
			boolean encontro = false;
			if (beneficiariosList != null && beneficiariosList.size() > 0) {
				for (Iterator i = beneficiariosList.iterator(); i.hasNext();) {
					objBeneVO = (BeneficiarioVO) i.next();
					if (strCode.equals(objBeneVO.getCode().toString())) {
						beneSelected.add(objBeneVO);
						encontro = true;
						break;
					}
				}
			}

			if (!encontro) {
				objBeneVO = new BeneficiarioVO();
				objBeneVO.setCode(new Long(strCode));
				try {
					beneSelected = beneficiarioServiceImpl
							.findBeneficiarioByCriteria(objBeneVO,
									"ConsultarBeneficiario");
					List<BeneficiarioVO> bene = (List<BeneficiarioVO>) beneSelected;
					objBeneVO = (BeneficiarioVO) bene.get(0);
				} catch (DAOException e) {
					System.err.println("/******** TDSUB - cwsub");
					e.printStackTrace();
					System.err.println("TDSUB - cwsub ********/");
				}
			}

			request.setAttribute("code", objBeneVO.getCode().toString());
			request.setAttribute("tipoDocumento", objBeneVO.getTipoDocumento());
			request.setAttribute("numeroDocumento",
					objBeneVO.getNumeroDocumento());
			request.setAttribute("primer_nombre", objBeneVO.getNombre1());
			request.setAttribute("segundo_nombre", objBeneVO.getNombre2());
			request.setAttribute("primerApellido",
					objBeneVO.getPrimerApellido());
			request.setAttribute("segundoApellido",
					objBeneVO.getSegundoApellido());
			request.setAttribute("telefono", objBeneVO.getTelefono());
			request.setAttribute("dirDescriptiva",
					objBeneVO.getDirDescriptiva());
			String dirEncasillada = objBeneVO.getDirEncasillada();
			// CR 0037 BB 0107 B 007 0001001
			// 0123456789012345678901234567891234
			if ((Object) dirEncasillada != null) {
				// int a = dirEncasillada.length();
				if (dirEncasillada.length() == 32) {
					String tipo = dirEncasillada.substring(0, 2);
					String vOr = dirEncasillada.substring(3, 4);
					String vNro = dirEncasillada.substring(4, 7);
					String vAp = dirEncasillada.substring(8, 10);
					String cOr = dirEncasillada.substring(13, 14);
					String cNro = dirEncasillada.substring(14, 17);
					String cAp = dirEncasillada.substring(18, 20);
					String placa = dirEncasillada.substring(21, 24);
					String bloque = dirEncasillada.substring(25, 27);
					String interior = dirEncasillada.substring(27, 32);
					request.setAttribute("tipo", tipo);
					request.setAttribute("vOr", vOr);
					request.setAttribute("vNro", vNro);
					request.setAttribute("vAp", vAp);
					request.setAttribute("cOr", cOr);
					request.setAttribute("cNro", cNro);
					request.setAttribute("cAp", cAp);
					request.setAttribute("placa", placa);
					request.setAttribute("bloque", bloque);
					request.setAttribute("interior", interior);
				} else {
					request.setAttribute("tipo", "");
					request.setAttribute("vOr", "");
					request.setAttribute("vNro", "");
					request.setAttribute("vAp", "");
					request.setAttribute("cOr", "");
					request.setAttribute("cNro", "");
					request.setAttribute("cAp", "");
					request.setAttribute("placa", "");
					request.setAttribute("bloque", "");
					request.setAttribute("interior", "");
				}
			}
			String strAddress = (String) request.getParameter("dirEncasillada");
			if (strAddress == null)
				strAddress = objBeneVO.getDirEncasillada();

			request.setAttribute("dirEncasillada", strAddress);
			request.setAttribute("barrio", objBeneVO.getCodeBarrio());
			request.setAttribute("zona", objBeneVO.getCodeZona());
			request.setAttribute("cobama", objBeneVO.getCobama());
			request.setAttribute("sexo", objBeneVO.getSexo());
			request.setAttribute("comuna", objBeneVO.getVflComuna());
			request.setAttribute("mail", objBeneVO.getMail());
			request.setAttribute("etnia", objBeneVO.getEtnia());
			String[] fenac = { "00", "00", "00" };
			if (objBeneVO.getFechaNacimiento() != null) {
				fenac = objBeneVO.getFechaNacimiento().split("/");
			}
			request.setAttribute("day", fenac[0]);
			request.setAttribute("month", fenac[1]);
			request.setAttribute("year", fenac[2]);
			request.setAttribute("beneSelected", beneSelected);
			try {
				Collection<BeneficiarioVO> grupo_familiar = beneficiarioServiceImpl
						.findGrupoFamiliar(objBeneVO);
				// session.setAttribute("grupo_familiar",grupo_familiar);
				request.setAttribute("grupo_familiar", grupo_familiar);
			} catch (DAOException e) {
				System.err.println("/******** TDSUB - cwsub");
				e.printStackTrace();
				System.err.println("TDSUB - cwsub ********/");
			}

			try {
				comunas = vflexServiceImpl.findVflex(VflexService.COMUNA);
				barrios = vflexServiceImpl.findVflex(VflexService.BARRIO);
				zonas = vflexServiceImpl.findVflex(VflexService.ZONA);

				hechosVictimizantes = vflexServiceImpl
						.findVflex(VflexService.HECHO_VICTIMIZANTE);
				System.out.println(hechosVictimizantes.toString());
				request.setAttribute("comunas", comunas);
				request.setAttribute("barrios", barrios);
				request.setAttribute("zonas", zonas);
				request.setAttribute("hechosVictimizantes", hechosVictimizantes);

				if ((Object) opcion != null) {
					if (opcion.equals("zona")) {
						String codeZona = request.getParameter("codeZona");
						comunas = vflexServiceImpl.findVflex(
								VflexService.COMUNA, codeZona);
						barrios = vflexServiceImpl
								.findVflex(VflexService.COMUNA);
						request.setAttribute("comunas", comunas);
						request.setAttribute("barrios", barrios);
						request.setAttribute("zonas", zonas);
						request.setAttribute("zona", codeZona);
					} else if (opcion.equals("comuna")) {
						String codeComuna = request.getParameter("vflComuna");
						String codeZona = request.getParameter("codeZona");
						String zona = "";
						if (codeZona.equals("")) {
							zona = vflexServiceImpl.findCodePadreByCodeHijo(
									new Long(codeComuna)).toString();
							request.setAttribute("zona", zona);
						} else {
							zona = codeZona;
							request.setAttribute("zona", codeZona);
						}
						comunas = vflexServiceImpl.findVflex(
								VflexService.COMUNA, zona);
						barrios = vflexServiceImpl.findVflex(
								VflexService.BARRIO, codeComuna);
						request.setAttribute("comuna", codeComuna);
						request.setAttribute("comunas", comunas);
						request.setAttribute("barrios", barrios);
						request.setAttribute("zonas", zonas);
					} else if (opcion.equals("barrio")) {
						String codeBarrio = request.getParameter("codeBarrio");
						barrios = vflexServiceImpl
								.findVflex(VflexService.BARRIO);
						request.setAttribute("barrios", barrios);
						comunas = vflexServiceImpl
								.findVflex(VflexService.COMUNA);
						request.setAttribute("comunas", comunas);

						String zona = "";
						String comuna = "";
						comuna = vflexServiceImpl.findCodePadreByCodeHijo(
								new Long(codeBarrio)).toString();

						request.setAttribute("comuna", comuna);
						if (!comuna.equals(""))
							zona = vflexServiceImpl.findCodePadreByCodeHijo(
									new Long(comuna)).toString();
						request.setAttribute("zona", zona);
						request.setAttribute("barrio", codeBarrio);
					}
				}
			} catch (DAOException e) {
				SUBException.logDebugError("", e);
			}
		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}
		}

		return mapping.findForward("success");
	}
}